package com.hoo.common.mock;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.io.FileUtil;
import cn.hutool.script.JavaScriptEngine;
import cn.hutool.script.ScriptUtil;

import java.io.File;


/**
 * 基于yod的数据库函数工具类
 *
 * @author hank
 * @create 2020-07-25 下午12:24
 * @deprecated 无法被引擎识别 - 待思考
 **/

public class YodDbUtil {

    private static Cache<String,String> lfuCache = CacheUtil.newLFUCache(1);
    private static JavaScriptEngine scriptEngine = ScriptUtil.getJavaScriptEngine();

    private static Object buildYod(String script) throws Exception {
        if(lfuCache.isEmpty()) {
            String yod = FileUtil.readUtf8String(new File("/Users/hank/WORK/hoo-platform-parent/hoo-base-parent/hoo-security-mock/src/main/resources/yod/yod-mock.min.js"));
            String db = FileUtil.readUtf8String(new File("/Users/hank/WORK/hoo-platform-parent/hoo-base-parent/hoo-security-mock/src/main/resources/yod/yod.db.js"));
            String js = new StringBuilder(yod).toString(); //.append(db).toString();
            lfuCache.put("scriptString", js, DateUnit.SECOND.getMillis() * 10);
            scriptEngine.eval(js);
        }
        return scriptEngine.eval(String.format("yod('%s')", script));
    }

    public static Object parse(String script) {
        try {
            return buildYod(script);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
